package io.vector.study.uploader.service;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * Created by vector on 2017/5/24.
 */
public interface IUploadHandler {

    String saveFile(MultipartFile multipartFile);

    String saveFileChunk(String fileId, MultipartFile multipartFile, int chunks, int chunk);

    String mergeFileChunks(String fileId);

    File getFile(String fileId);

    default String calcStoreFileName(String originFileName) {
        return originFileName;
    }

    default String calcStoreFileName(String originFileName, int chunks, int chunk) {
//        String baseName = FilenameUtils.getBaseName(originFileName);
//        String extension = FilenameUtils.getExtension(originFileName);
//        if (StringUtils.isEmpty(extension)) {
//            return String.format("%s_%s_%s", baseName, chunks, chunk);
//        } else {
//            return String.format("%s_%s_%s.%s", baseName, chunks, chunk);
//        }
        return String.format("%s.%s", originFileName, chunk);
    }

    default String parseFileName(String fileChunkName) {
        int chunkSplitIndex = fileChunkName.lastIndexOf(".");
        if (chunkSplitIndex != -1) {
            return fileChunkName.substring(0, chunkSplitIndex);
        } else {
            return fileChunkName;
        }
    }

    default void storeFile(MultipartFile multipartFile, File destFile) {
        try {
            if (!destFile.exists()) {
                FileUtils.forceMkdirParent(destFile);
            }
            multipartFile.transferTo(destFile);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
